package com.alone.embedded.lucene.spring;

import com.alone.embedded.lucene.exception.EmbeddedLuceneException;
import com.alone.embedded.lucene.spring.annotation.ElTransactional;
import com.alone.embedded.lucene.transaction.ElTransactionDef;
import com.alone.embedded.lucene.transaction.ElTransactionTemplate;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

/**
 * @author Alone
 * @date 2022/9/2 3:44 下午
 */
@Aspect
@RequiredArgsConstructor
public class ElTransactionAspect {

    private final ElTransactionTemplate txTemplate;

    @Around("@annotation(elTransactional) || @within(elTransactional)")
    public Object doTransaction(ProceedingJoinPoint joinPoint, ElTransactional elTransactional) {
        return txTemplate.execute(() -> {
            try {
                return joinPoint.proceed();
            } catch (Throwable e) {
                throw EmbeddedLuceneException.of(e);
            }
        }, getDef(elTransactional));
    }

    private ElTransactionDef getDef(ElTransactional elTransactional) {
        return new ElTransactionDef(elTransactional.timeout(), elTransactional.rollbackFor());
    }

}
